package cn.yangliu.web;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yangliu.config.custom.TokenAuthenticationFilter;
import cn.yangliu.config.custom.TokenStore;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 自定义登录
 *
 * @author 杨柳
 * @date 2019-06-01
 */
@Controller
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    protected ApplicationEventPublisher eventPublisher;
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
    private SessionAuthenticationStrategy sessionStrategy;

    {
        authenticationDetailsSource = new WebAuthenticationDetailsSource();
        sessionStrategy = new NullAuthenticatedSessionStrategy();
    }



    @PostMapping("/auth")
    @ApiOperation("登录")
    @SneakyThrows
    public void auth(HttpServletRequest request, HttpServletResponse response,
                     String username, String password) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        authenticationToken.setDetails(authenticationDetailsSource.buildDetails(request));
        authenticationManager.authenticate(authenticationToken);
        sessionStrategy.onAuthentication(authenticationToken, request, response);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authenticationToken, this.getClass()));

        authenticationSuccessHandler.onAuthenticationSuccess(request, response, authenticationToken);

    }

}
